import os
import asyncio
import json
from datetime import datetime, date, time
from collections import deque
from fastapi import APIRouter, WebSocket, WebSocketDisconnect
from websockets.exceptions import ConnectionClosedOK, ConnectionClosedError
from fastapi import APIRouter, Query, Request
from fastapi.templating import Jinja2Templates

router = APIRouter()



connected_clients = []
time_series = deque(maxlen=12)

async def generate_data():
    now = datetime.now()
    today_start = datetime.combine(date.today(), time.min)
    # 查询所有状态为 成功、失败、运行中 且在今天范围内的记录
    jobs = await JobRecords.filter(
        exec_start_time__gte=today_start,
        exec_start_time__lte=now,
        result_status__in=["成功", "失败", "运行中"]
    ).values("result_status", "app_name", "exec_start_time", "exec_end_time", "exec_duration", "result_detail")

    # 统计结果
    counter = {
        "success": 0,
        "failed": 0,
        "running": 0
    }
    rpa_tasks = []
    for job in jobs:
        status = job["result_status"]
        if status == "成功":
            counter["success"] += 1
        elif status == "失败":
            counter["failed"] += 1
        elif status == "运行中":
            counter["running"] += 1

        rpa_tasks.append({
            "app_name": job["app_name"],
            "status": job["result_status"],
            "start_time": job["exec_start_time"].strftime("%Y-%m-%d %H:%M:%S"),
            "end_time": job["exec_end_time"].strftime("%Y-%m-%d %H:%M:%S") if job["exec_end_time"] else None,
            "duration": job["exec_duration"],
            "error_reason": job["result_detail"]
        })
        
        

    result =  {
        "time": now.strftime("%H:%M:%S"),
        **counter
    }

    
    time_series.append(result)

    data = {"summary": result,
            "rpa_tasks":rpa_tasks,
            "time_series": list(time_series),
            "timestamp": now.strftime("%Y-%m-%d %H:%M:%S")}
    return data


@router.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
    await websocket.accept()
    connected_clients.append(websocket)
    try:
        while True:
            # Send data every 5 seconds
            data = await generate_data()
            # print("data",json.dumps(data,ensure_ascii=False))
            await websocket.send_json(data)
            await asyncio.sleep(5)
    except (WebSocketDisconnect, ConnectionClosedOK, ConnectionClosedError):
        # Handle normal client disconnection
        if websocket in connected_clients:
            connected_clients.remove(websocket)
    except Exception as e:
        # Handle other exceptions
        print(f"WebSocket error: {str(e)}")
        if websocket in connected_clients:
            connected_clients.remove(websocket)